﻿Public Class SelectPar

  'переменные импорта
  Public SqlStr As String   'sql запрос c двумя полями, 1-значение, 2-наименование
  Public ColName As String  'Наименование столбца в таблице
  Public SelID As String    'параметр для выбора строки по умолчанию

  'возвращаем при выборе
  Public flSel As Boolean   'флаг выбора параметра
  Public SelName As String  'наименование выбранного параметра
  Public SelValue As String 'значение выбранного параметра

  'быстрый поиск
  Private SqlFastSearch As String

  'имя столбца с наименованием параметра - по нему будем делать быстрый поиск
  Private ParColNameValue As String


  Private Sub SelectPar_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    InitForm()

  End Sub


  ''' <summary>
  ''' Инициализация элементов формы
  ''' </summary>
  ''' <remarks></remarks>
  Private Sub InitForm()

    'перенаправляем событие с DGV 
    AddHandler DGV.KeyDown, AddressOf DGV_KeyDown
    AddHandler DGV.CellPainting, AddressOf DGV_CellPainting

    'события поисковой строки
    AddHandler StrSearch.Enter, AddressOf StrFind_Enter
    AddHandler StrSearch.Leave, AddressOf StrFind_Leave
    StrSearch.Text = Params.StrSearchLabel


    If ColName = "" Then ColName = "Значение параметра"

    Dim colTextBox As New DataGridViewTextBoxColumn
    colTextBox.HeaderText = ColName
    colTextBox.Name = "ParValue"
    colTextBox.MinimumWidth = 100
    colTextBox.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
    DGV.Columns.Add(colTextBox)

  End Sub

  ''' <summary>
  ''' Загрузка данных 
  ''' </summary>
  ''' <remarks></remarks>
  Private Sub LoadData()

    DGV.Rows.Clear()

    'фильтр добавлять в основной запрос, быстрый поиск в обертке....
    '+ быстрый поиск...
    Dim DRC As DataRowCollection

    DRC = DB.GetFields(SqlStr + SqlFastSearch)

    If DRC Is Nothing = False Then

      If ParColNameValue = "" Then ParColNameValue = DRC(0).Table.Columns(1).ColumnName

      For Each dr As DataRow In DRC

        AddRowInDGV(dr)

        If DGV.Rows.Count Mod 2 = 0 Then
          Application.DoEvents()
        End If

      Next

    End If

    CountRowsDGBLabel.Text = "Строк в таблице: " + String.Format("{0:N0}", DGV.Rows.Count)

  End Sub

  ''' <summary>
  ''' Добавление строки с данными в DGV
  ''' </summary>
  ''' <param name="dr"></param>
  ''' <remarks></remarks>
  Private Sub AddRowInDGV(ByVal dr As DataRow)

    Dim DGVRow As DataGridViewRow

    DGV.Rows.Add()
    DGVRow = DGV.Rows(DGV.Rows.GetLastRow(DataGridViewElementStates.Visible))
    DGVRow.Tag = dr(0).ToString()
    DGVRow.Cells("ParValue").Value = dr(1).ToString()

    'выбор параметра по умолчанию
    If SelID <> "" And dr(0).ToString() = SelID Then
      DGV.ClearSelection()
      DGVRow.Selected = True
      DGVRow.Cells(0).Selected = True
    End If

  End Sub


#Region "Быстрый поиск"

  Private Sub FastSearch(ByVal s As String)

    s = DB.SetQuotes(s.Trim().ToLower())

    Dim flFilter As Boolean

    If s.Length < 3 Then

      If SqlFastSearch <> "" Then
        SqlFastSearch = ""
        flFilter = True
      End If

    Else

      SqlFastSearch = " WHERE "
      SqlFastSearch += String.Format(" CHARINDEX('{0}', {1}) <> 0", s, ParColNameValue)

      flFilter = True

    End If

    If flFilter Then
      LoadData()
    End If

  End Sub

  Private Sub StrSearch_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles StrSearch.KeyDown

    FastSearchTimer.Enabled = False

  End Sub


  Private Sub StrSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StrSearch.TextChanged

    If StrSearchLabel = StrSearch.Text Or StrSearch.Tag = StrSearch.Text Then Exit Sub

    StrSearch.Tag = StrSearch.Text
    FastSearchTimer.Enabled = True

  End Sub


  Private Sub FastSearchTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FastSearchTimer.Tick

    FastSearchTimer.Enabled = False
    FastSearch(StrSearch.Text)

  End Sub

#End Region


  ''' <summary>
  ''' выбор параметра
  ''' </summary>
  ''' <remarks></remarks>
  Private Sub doSelect()

    If DGV.SelectedRows.Count = 0 Then Exit Sub

    SelValue = DGV.SelectedRows(0).Tag.ToString()
    SelName = DGV.SelectedRows(0).Cells("ParValue").Value.ToString()

    flSel = True

    Me.Close()

  End Sub


  ''СОБЫТИЯ:

  Private Sub SelectPar_Shown(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Shown

    LoadData()

  End Sub

  Private Sub DGV_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV.CellDoubleClick

    doSelect()

  End Sub

  Private Sub МенюВыбрать_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles МенюВыбрать.Click

    doSelect()

  End Sub

  Private Sub tbtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbtnSave.Click

    doSelect()

  End Sub

  Private Sub tbtnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbtnClose.Click

    Me.Close()

  End Sub

  Private Sub МенюЗакрыть_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles МенюЗакрыть.Click

    Me.Close()

  End Sub

  Private Sub SelectPar_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown

    If e.KeyCode = Keys.Escape Then Me.Close()

    If e.KeyCode = Keys.F2 Then doSelect()

  End Sub

  Private Sub DGV_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DGV.KeyDown

    If e.KeyCode = Keys.Return Then doSelect()

  End Sub


End Class